<template>
  <div class="flex">
    <div class="tableManage w-100%">
      <!-- <ContentWrap> -->
        <!-- 搜索区域 -->
        <div class="search-form">
          <Search
            :schema="allSchemas.searchSchema"
            @reset="setSearchParams"
            @search="setSearchParams"
          />
        </div>

        <ElDivider />
        <!-- <div class="line"></div> -->

        <!-- 操作按钮区域 -->
        <div class="mb-10px">
          <!-- <BaseButton

            class="opBtn"
            size=""
            type="primary"
            @click="AddAction"
          >
            新增
          </BaseButton> -->
          <BaseButton
            v-if="
              deviceTreeStore.currentNodeKey && currentNodeType === '设备型号'
            "
            class="opBtn"
            size=""
            type="primary"
            @click="AddAction"
          >
            新增
          </BaseButton>
          <BaseButton class="opBtn" size="" type="primary" @click="showFillTips">
            填报提示
          </BaseButton>
        </div>

        <!-- 数据表格 -->
        <Table
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :columns="allSchemas.tableColumns"
          :data="dataList"
          :loading="loading"
          @register="tableRegister"
          :pagination="{ total }"
        />
      <!-- </ContentWrap> -->
    </div>

    <!-- 新增/编辑/查看对话框 -->
    <Dialog width="65%" v-model="dialogVisible" :title="dialogTitle">
      <!-- 表单组件（新增/编辑时显示） -->
      <Write
        class="opWrite"
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
        :current-node-name="currentNodeName"
      />

      <!-- 详情组件（查看时显示） -->
      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <!-- 对话框底部按钮 -->
      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          保存
        </BaseButton>
        <BaseButton @click="dialogVisible = false">关闭</BaseButton>
      </template>
    </Dialog>

       <!-- 新增：填报提示弹框 -->
    <Dialog
      v-model="fillTipsVisible"
      title="国产元器件填报要求"
      width="700px"

    >
      <div class="fill-tips-content">
        <div class="tips-section">

          <div class="tips-item">
            <div v-html="fillTipsData"></div>
          </div>
        </div>
      </div>

      <template #footer>
        <BaseButton type="primary" @click="fillTipsVisible = false">确定</BaseButton>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="tsx">
import {
  ref,
  unref,
  reactive,
  watch,
  computed,
  onMounted,
  ComponentRef,
  nextTick,
} from "vue";
import { ContentWrap } from "@/components/ContentWrap";
import { Table } from "@/components/Table";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search } from "@/components/Search";
import Write from "./components/domesticComponentsWrite.vue";
import { useValidator } from "@/hooks/web/useValidator";
import Detail from "./components/domesticComponentsDetail.vue";
import { Dialog } from "@/components/Dialog";
import { CrudSchema, useCrudSchemas } from "@/hooks/web/useCrudSchemas";
import { BaseButton } from "@/components/Button";
import { useDeviceTreeStore } from "@/store/modules/deviceTreeStore";
import { useDictionaryStore } from "@/store/modules/dictionaryStore";
import { Edit, View, Delete } from "@element-plus/icons-vue";
import { useTable } from "@/hooks/web/useTable";
import { directAxios } from "@/axios/index";
import { debounce } from "lodash-es";
import { FORM_TYPES } from "@/utils/tips";
// import { useDeviceUtils } from '@/hooks/web/useDeviceUtils'
// import fillTipsData from '../../../../public/tips.json'; // 新增：导入JSON文件
// ============ 初始化Store和工具函数 ============
// const { getDeviceNameByCode, clearDeviceNameCache } = useDeviceUtils()
const dictionaryStore = useDictionaryStore(); // 字典store
const deviceTreeStore = useDeviceTreeStore(); // 设备树store
const { required } = useValidator(); // 表单验证工具

// ============ 响应式数据定义 ============

// 当前节点相关
const currentNodeName = ref(""); // 当前节点名称
const currentNodeType = ref(""); // 当前节点类型
const currentNodeKey = ref(deviceTreeStore.currentNodeKey); // 当前节点key
const currentNodeKeys = ref(); // 当前节点keys

// 防抖和加载控制
const loadingLock = ref(false);
const lastRequestKey = ref(""); // 记录最后一次请求的key
let currentRequestId = 0; // 请求ID追踪

// ============ 新增：填报提示相关数据 ============
// ============ 填报提示相关数据 ============
const fillTipsVisible = ref(false); // 填报提示弹框显示状态
const fillTipsData = ref(""); // 填报提示内容
const fillTipsLoading = ref(false); // 加载状态

/**
 * 加载填报提示数据
 */
const loadFillTipsData = async (): Promise<string> => {
  try {
    fillTipsLoading.value = true;
    const BASE_URL = import.meta.env.VITE_APP_BASE_URL || '/'
      const response = await fetch(`${BASE_URL}tips.json`);
    console.log(response,7890);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    return data[FORM_TYPES.DOMESTIC_COMPONENTS] || "暂无填报提示信息";
  } catch (error) {
    console.error('加载填报提示数据失败:', error);
    return "加载填报提示信息失败，请稍后重试";
  } finally {
    fillTipsLoading.value = false;
  }
}

/**
 * 显示填报提示弹框
 */
const showFillTips = async () => {
  try {
    fillTipsVisible.value = true;
    // 每次显示都重新加载，确保获取最新数据
    fillTipsData.value = await loadFillTipsData();
  } catch (error) {
    console.error('显示填报提示失败:', error);
    fillTipsData.value = "加载填报提示信息失败，请稍后重试";
  }
};

// 表格相关状态 - 使用useTable hook管理表格状态
const { tableRegister, tableState, tableMethods } = useTable({
  /**
   * 获取表格数据的API
   */
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState;
    const deviceCode = deviceTreeStore.currentNodeKey;

    // 如果没有选中设备节点或任务，返回空数据
    if (!deviceCode || !deviceTreeStore.currentTask) {
      return {
        list: [],
        total: 0,
      };
    }

    const res = await "/cDomesticComponents/page".get({
      deviceCode: deviceCode,
      missionCode: deviceTreeStore.taskInfo?.missionCode,
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams),
    });
    return {
      list: res.data.records || [],
      total: res.data.total || 0,
    };
  },
  immediate: false, // 禁用立即执行
});

// 解构表格状态和方法
const { total, loading, dataList, pageSize, currentPage } = tableState;
const { getList, delList } = tableMethods;

// 搜索参数
const searchParams = ref({
  classificationCode: "",
});

// 对话框相关状态
const dialogVisible = ref(false); // 对话框显示状态
const dialogTitle = ref(""); // 对话框标题
const currentRow = ref(); // 当前操作的行数据
const actionType = ref(""); // 操作类型：'' | 'edit' | 'detail'
const saveLoading = ref(false); // 保存加载状态

// 组件引用
const writeRef = ref<ComponentRef<typeof Write>>(); // 表单组件引用

// ============ 计算属性 ============

// 类别选项
const classificationOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(
      dictionaryStore.DICTIONARY_TYPES.COM_CLASSIFICATION
    ) || []
  );
});

// 自主可控等级选项
const controllableOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(
      dictionaryStore.DICTIONARY_TYPES.INDEPENDENT_CONTROL_LEVEL
    ) || []
  );
});

// 是否核心关键元器件选项
const coreKeyOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(dictionaryStore.DICTIONARY_TYPES.YORN) ||
    []
  );
});

// 是否为WKB选项
const isWkbOptions = computed(() => {
  return (
    dictionaryStore.dictionaries.get(dictionaryStore.DICTIONARY_TYPES.IS_WKB) ||
    []
  );
});

// ============ 防抖和安全获取方法 ============

/**
 * 防抖的获取列表方法
 */
const getListDebounced = debounce(async () => {
  if (loadingLock.value || loading.value) return;

  const currentKey = deviceTreeStore.currentNodeKey;
  if (!currentKey || !deviceTreeStore.currentTask) {
    dataList.value = [];
    total.value = 0;
    return;
  }

  // 如果和上次请求的key相同，且数据已存在，则不重复请求
  const requestSignature = `${currentKey}-${deviceTreeStore.currentTask}`;
  if (lastRequestKey.value === requestSignature && dataList.value.length > 0) {
    return;
  }

  loadingLock.value = true;
  lastRequestKey.value = requestSignature;

  try {
    await getList();
  } finally {
    loadingLock.value = false;
  }
}, 300);

/**
 * 安全获取方法
 */
const getListSafe = async () => {
  if (loadingLock.value) {
    return;
  }

  if (!deviceTreeStore.currentNodeKey || !deviceTreeStore.currentTask) {
    dataList.value = [];
    total.value = 0;
    return;
  }

  getList();
};

// ============ 监听器 ============

/**
 * 监听任务变化，当任务切换时刷新数据
 */
watch(
  () => deviceTreeStore.currentTask,
  async (newTask, oldTask) => {
    if (newTask && newTask !== oldTask) {
      currentPage.value = 1; // 重置分页
      dataList.value = []; // 清空旧数据
      searchParams.value = { classificationCode: "" }; // 重置搜索条件

      // 使用nextTick确保在下一个事件循环执行
      await nextTick();

      // 生成新的请求ID
      const requestId = ++currentRequestId;

      // 使用setTimeout确保在浏览器空闲时执行
      setTimeout(() => {
        // 检查是否仍然是最新的请求
        if (requestId === currentRequestId) {
          getListSafe();
        }
      }, 0);
    }
  }
);

/**
 * 监听设备树节点变化，刷新表格数据 - 主监听器
 */
watch(
  () => deviceTreeStore.currentNodeKey,
  async (newKey, oldKey) => {
    const node = deviceTreeStore.currentTreeNode;
    console.log("设备树节点变化:", node.nodeType);

    currentNodeKey.value = newKey;
    currentNodeKeys.value = newKey;
    currentNodeName.value = node?.deviceName || "";
    currentNodeType.value = node?.nodeType || ""; // 设置当前节点类型

    // 只有当节点真正变化时才刷新数据
    if (newKey && newKey !== oldKey) {
      currentPage.value = 1;
      dataList.value = []; // 清空旧数据
      searchParams.value = { classificationCode: "" }; // 重置搜索条件

      // 使用nextTick确保在下一个事件循环执行
      await nextTick();

      // 生成新的请求ID
      const requestId = ++currentRequestId;

      // 使用setTimeout确保在浏览器空闲时执行
      setTimeout(() => {
        // 检查是否仍然是最新的请求
        if (requestId === currentRequestId) {
          getListSafe();
        }
      }, 0);
    }
  },
  { immediate: true, flush: "post" } // 使用post确保在DOM更新后执行
);

// ============ 方法定义 ============

/**
 * 设置搜索参数并刷新表格
 * @param params 搜索参数
 */
const setSearchParams = (params: any) => {
  currentPage.value = 1;
  searchParams.value = {
    ...params,
    classificationCode: params.category?.[params.category.length - 1] || "",
  };
  getList();
};

/**
 * 新增操作
 */
const AddAction = () => {
  if (currentNodeType.value !== "设备型号") {
    ElMessage.error("仅设备节点可新增");
    return;
  }
  dialogTitle.value = "新增";
  currentRow.value = {
    account: currentNodeName.value, // 设置所属设备名称
  };
  dialogVisible.value = true;
  actionType.value = "";
};

/**
 * 删除数据
 * @param row 要删除的行数据
 */
const delData = async (row?: any) => {
  ElMessageBox.confirm("是否确认删除?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const params = {
        id: row?.id,
      };
      const res = await directAxios.post(
        "/cDomesticComponents/delete",
        params,
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          transformRequest: [(data) => data.toString()],
        }
      );

      if (res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      }
    })
    .catch(() => {});
};

/**
 * 行操作处理（编辑/查看）
 * @param row 行数据
 * @param type 操作类型：'edit' | 'detail'
 */
const action = (row, type: string) => {
  dialogTitle.value = type === "edit" ? "编辑" : "查看";
  actionType.value = type;

  // 处理分类代码为空的情况
  row.classificationCode === undefined ||
  row.classificationCode == "" ||
  row.classificationCode == null
    ? (row.classificationCode = "")
    : row.classificationCode;

  // 根据分类代码长度构建级联选择器数据
  const data =
    row.classificationCode.length == 8
      ? [
          row.classificationCode.slice(0, 4) || "",
          row.classificationCode.slice(0, 6) || "",
          row.classificationCode || "",
        ]
      : row.classificationCode.length == 6
        ? [
            row.classificationCode.slice(0, 4) || "",
            row.classificationCode.slice(0, 6) || "",
          ]
        : [row.classificationCode.slice(0, 4) || ""];
  // 关键修改：根据设备编码查找实际的设备名称
  // const actualDeviceName = getDeviceNameByCode(row.deviceCode);
  // const actualDeviceName = getDeviceNameByCode(row.deviceCode);
  const actualDeviceName = deviceTreeStore.getDeviceNameByCode(row.deviceCode);
  currentRow.value = {
    ...row,
    category: data,
     account: actualDeviceName, // 使用实际所属的设备名称
  };
  dialogVisible.value = true;
};

/**
 * 保存表单数据
 */
const save = async () => {
  const write = unref(writeRef);
  const formData = await write?.submit();

  if (formData) {
    saveLoading.value = true;
    try {
      const res = await "/cDomesticComponents/save".post({
        ...formData,
        category: "", // 清空category字段
        classification1: currentRow.value.classification1 || "",
        classification2: currentRow.value.classification2 || "",
        classification3: currentRow.value.classification3 || "",
        deviceCode: currentNodeKeys.value, // 设置设备编码
        missionCode: deviceTreeStore.taskInfo?.missionCode,
      });

      if (res) {
        currentPage.value = 1;
        getList();
        ElMessage.success("保存成功");
        dialogVisible.value = false;
      }
    } catch (error) {
      console.error("保存失败:", error);
    } finally {
      saveLoading.value = false;
    }
  }
};

/**
 * 处理类别选择变化
 * @param value 选中的值数组
 */
const handleCategoryChange = (value) => {
  const selectedOptions = getCascaderObj(
    value,
    dictionaryStore.dictionaries.get(
      dictionaryStore.DICTIONARY_TYPES.COM_CLASSIFICATION
    )
  );

  if (!currentRow.value) {
    currentRow.value = {};
  }

  // 清空之前的分类数据
  currentRow.value.classification1 = "";
  currentRow.value.classification2 = "";
  currentRow.value.classification3 = "";
  currentRow.value.classificationCode = "";
  currentRow.value.category = value;
  currentRow.value.classificationCode =
    selectedOptions[selectedOptions.length - 1].code;

  // 根据选中的层级设置对应的分类字段
  if (selectedOptions.length > 0) {
    currentRow.value.classification1 = selectedOptions[0]?.text || "";
  }
  if (selectedOptions.length > 1) {
    currentRow.value.classification2 = selectedOptions[1]?.text || "";
  }
  if (selectedOptions.length > 2) {
    currentRow.value.classification3 = selectedOptions[2]?.text || "";
  }
};

/**
 * 工具函数：根据值和选项获取级联选择器对象
 * @param val 选中的值数组
 * @param opt 选项数组
 * @returns 选中的选项对象数组
 */
const getCascaderObj = (val, opt) => {
  return val.map(function (value, index, array) {
    for (var itm of opt) {
      if (itm.code == value) {
        opt = itm.children;
        return itm;
      }
    }
    return null;
  });
};
/**
 * 根据设备编码获取设备名称
 * @param deviceCode 设备编码
 * @returns 设备名称
 */
// const getDeviceNameByCode = (deviceCode: string): string => {
//   console.log("设备编码:", deviceTreeStore.currentTreeNode);

//   if (!deviceCode) return currentNodeName.value;

//   // 递归查找设备节点
//   const findNode = (nodes: any[], code: string): any => {

//     if (!nodes || !Array.isArray(nodes)) return null;
//     for (const node of nodes) {
//       if (node.deviceCode === code) {
//         return node;
//       }
//       if (node.children && Array.isArray(node.children)) {
//         const found = findNode(node.children, code);
//         if (found) return found;
//       }
//     }
//     return null;
//   };

//   // 从设备树store中查找
//   const deviceNode = findNode([deviceTreeStore.currentTreeNode]|| [], deviceCode);
//   return deviceNode?.deviceName || '未知设备';
// };
// ============ CRUD表结构配置 ============

/**
 * 国产元器件管理表结构配置
 */
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: "selection",
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: "selection", hidden: true },
  },
  {
    field: "index",
    label: "序号",
    form: { hidden: true },
    search: { hidden: true },
    detail: { hidden: true },
    table: { type: "index" },
  },
  {
    field: "account",
    label: "所属设备",
    width: 90,
    search: { hidden: true },
    form: {
      component: "Input",
      // value: currentNodeName.value,
      componentProps: {
        placeholder: "请输入所属设备",
        disabled: true,
      },
    },
   table: {
    hidden: true,

  },
  detail: {
    // 在详情中也动态显示设备名称
    // formatter: (row: any) => {
    //   return getDeviceNameByCode(row.deviceCode);
    // }
  },
  },
  {
    field: "classificationCode",
    width: 100,
    label: "分类代码",
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    form: {
      componentProps: {
        placeholder: "分类代码将自动生成",
        disabled: true,
      },
      formItemProps: { rules: [required()] },
    },
    search: { hidden: true },
  },
  {
    field: "category",
    label: "类别",
    width: 250,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: {
      component: "Cascader",

      componentProps: {
        placeholder: "类别",
        filterable: true,
        options: classificationOptions,
        props: {
          checkStrictly: false,
          emitPath: true,
          label: "text",
          value: "code",
        },
      },
    },
    form: {
      component: "Cascader",
      formItemProps: {
        rules: [{ required: true, message: "请选择类别" }],
      },
      componentProps: {
        placeholder: "请选择类别",
        filterable: true,
        options: classificationOptions,
        props: {
          checkStrictly: false,
          emitPath: true,
          label: "text",
          value: "code",
        },
        onChange: (value: any[]) => {
          handleCategoryChange(value);
        },
      },
    },
    detail: { hidden: true },
    table: {
      formatter: (row: any) => {
        // 组合分类字段，用 > 分隔，空值用 / 代替
        const parts = [
          row.classification1 || "/",
          row.classification2 || "/",
          row.classification3 || "/",
        ];
        if (row.classificationCode.length == 4) {
          return row.classification1;
        } else if (row.classificationCode.length == 6) {
          return row.classification1 + " > " + row.classification2;
        } else if (row.classificationCode.length == 8) {
          return parts.join(" > ");
        }
      },
    },
  },
  {
    field: "classification1",
    label: "一级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "classification2",
    label: "二级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "classification3",
    label: "三级类别",
    width: 90,
    search: { hidden: true },
    form: { hidden: true },
    table: { hidden: true },
  },
  {
    field: "componentName",
    label: "元器件名称",
    width: 150,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "元器件名称" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入元器件名称" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入元器件名称" },
        ],
      },
      componentProps: { placeholder: "请输入元器件名称" },
    },
  },
  {
    field: "modelSpecification",
    label: "型号规格",
    width: 120,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "型号规格" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入型号规格" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入型号规格" },
        ],
      },
      componentProps: { placeholder: "请输入型号规格" },
    },
  },
  {
    field: "manufacturer",
    label: "生产厂商",
    width: 150,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "生产厂商" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入生产厂商" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入生产厂商" },
        ],
      },
      componentProps: { placeholder: "请输入生产厂商" },
    },
  },
  {
    field: "qualityLevel",
    label: "质量等级",
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: {
      component: "Input",
      label: "",
      hidden: false,
      componentProps: { placeholder: "质量等级" },
    },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入质量等级" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入质量等级" },
        ],
      },
      componentProps: { placeholder: "请输入质量等级" },
    },
  },
  {
    field: "independentControlLevel",
    label: "自主可控等级",
    width: 140,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: {
      component: "Select",
      label: "自主可控等级",
      hidden: false,
      componentProps: {
        placeholder: "自主可控等级",
        options: controllableOptions,
      },
    },
    form: {
      component: "Select",
      value: "",
      componentProps: { options: controllableOptions },
      formItemProps: {
        rules: [{ required: true, message: "请选择自主可控等级" }],
      },
    },
  },
  {
    field: "coreIndicators",
    label: "核心指标",
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      colProps: { span: 24 },
      formItemProps: {
        rules: [
          { required: true, message: "请输入核心指标" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入核心指标" },
        ],
      },
    },
    detail: { span: 24 },
  },
  {
    field: "testingOrganization",
    label: "元器件检测机构",
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    detail: { span: 24 },
    form: {
      component: "Input",
      componentProps: { placeholder: "请输入元器件检测机构" },
      colProps: { span: 24 },
      formItemProps: {
        rules: [
          { required: true, message: "请输入元器件检测机构" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入元器件检测机构" },
        ],
      },
    },
  },
  {
    field: "quantityPerDevice",
    label: "单个设备使用该产品数量",
    width: 90,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "InputNumber",
      formItemProps: {
        rules: [
          { required: true, message: "请输入使用数量" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        placeholder: "请输入使用数量",
        type: "number",
        min: 0,
        step: 1,
        precision: 0, // 精度为0，即整数
      },
    },
  },
  {
    field: "isCoreComponent",
    label: "是否核心关键元器件",
    width: 180,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    form: {
      component: "Select",
      value: "是",
      componentProps: { options: coreKeyOptions },
      formItemProps: {
        rules: [{ required: true, message: "请选择是否核心关键元器件" }],
      },
    },
    search: {
      component: "Select",
      label: "是否核心关键元器件",
      hidden: false,
      componentProps: {
        placeholder: "是否核心关键元器件",
        options: coreKeyOptions,
      },
    },
  },
  {
    field: "referencePrice",
    label: "参考价格(元)",
    width: 120,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入参考价格" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        type: "number",
        placeholder: "请输入参考价格",
        min: 0,
      },
    },
  },
  {
    field: "supplyCycle",
    label: "供货周期(周)",
    width: 120,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: { hidden: true },
    form: {
      component: "InputNumber",
      formItemProps: {
        rules: [
          { required: true, message: "请输入供货周期" },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error("输入值不能低于 0"));
              }
              callback();
            },
          },
        ],
      },
      componentProps: {
        type: "number",
        placeholder: "请输入供货周期",
        min: 1,
        precision: 0, // 精度为0，即整数
        step: 1,
      },
    },
  },
  {
    field: "historicalApplication",
    label: "历史应用信息",
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    width: 90,
    search: { hidden: true },
    table: { hidden: true },
    form: {
      component: "Input",
      colProps: { span: 24 },
      componentProps: {
        type: "textarea",
        rows: 3,
        placeholder: "请输入历史应用信息",
      },
    },
    detail: { span: 24 },
  },
  {
    field: "isWkb",
    label: "是否WKB",
    width: 90,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    form: {
      component: "Select",
      value: "",
      componentProps: { options: isWkbOptions },
      formItemProps: {
        rules: [{ required: true, message: "请选择是否WKB" }],
      },
    },
    search: {
      component: "Select",
      label: "是否WKB",
      hidden: false,
      componentProps: {
        placeholder: "是否WKB",
        options: isWkbOptions,
      },
    },
    // table: { hidden: true },
  },
  {
    field: "isPre",
    label: "是否优选",
    width: 90,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    form: {
      hidden: true,
    },
    // table: { hidden: true },
    search: {
      component: "Select",
      label: "是否优选",
      hidden: false,
      componentProps: {
        placeholder: "是否优选",
        options: [
          { label: "是", value: "1" },
          { label: "否", value: "0" },
        ],
      },
    },
  },
  {
    field: "packagingType",
    label: "封装形式",
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    width: 120,
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入封装形式" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入封装形式" },
        ],
      },
      componentProps: { placeholder: "请输入封装形式" },
    },
  },
  {
    field: "personInCharge",
    label: "负责人",
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: { hidden: true },
    form: {
      component: "Input",
      formItemProps: {
        rules: [
          { required: true, message: "请输入负责人" },
          { pattern: /^(?!\s*$)(?!\/+$).+$/, message: "请输入负责人" },
        ],
      },
      componentProps: { placeholder: "请输入负责人" },
    },
  },
  {
    field: "contactInfo",
    label: "联系方式",
    width: 120,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: { hidden: true },
    form: {
      component: "Input",
      componentProps: { placeholder: "请输入联系方式" },
      formItemProps: {
        rules: [
          { required: true, message: "请输入联系方式" },
          {
            pattern: /^[0-9]{11}$/,
            message: "请输入正确的联系方式"
            // pattern:
            //   /^(?:(?:\d{11})|(?:\d{3,4}-\d{7,8})(?:-\d+)?|(?:\d{7,8})(?:-\d+)?)$/,
            // message:
            //   "手机号格式：11位数字，座机号格式：区号-号码 或 7-8位号码，可加分机号",
          },
        ],
      },
      colProps: { span: 12 },
    },
    detail: { span: 24 },
  },
  {
    field: "remarks",
    label: "备注",
    width: 90,
    showTip: true, // 启用提示
    tipConfig: {
      formType: FORM_TYPES.DOMESTIC_COMPONENTS,
    },
    search: { hidden: true },
    detail: { span: 24 },
    form: {
      component: "Input",
      componentProps: {
        type: "textarea",
        rows: 3,
        placeholder: "请输入备注信息",
      },
      colProps: { span: 24 },
    },
    table: { hidden: true },
  },
  {
    field: "action",
    label: "操作",
    fixed: "right",
    form: { hidden: true },
    detail: { hidden: true },
    search: { hidden: true },
    table: {
      width: 170,
      fixed: "right",
      slots: {
        default: (data: any) => {
          const row = data.row;
          return (
            <>
              <div style="display:flex;color: var(--el-color-primary)">
                <div
                  class="flex-1 cursor-pointer"
                  onClick={() => action(row, "edit")}
                >
                  <el-icon>
                    <Edit />
                  </el-icon>
                  编辑
                </div>
                <div
                  class="flex-1 cursor-pointer"
                  onClick={() => action(row, "detail")}
                >
                  <el-icon>
                    <View />
                  </el-icon>
                  查看
                </div>
                <div class="flex-1 cursor-pointer" onClick={() => delData(row)}>
                  <el-icon>
                    <Delete />
                  </el-icon>
                  删除
                </div>
              </div>
            </>
          );
        },
      },
    },
  },
]);

// 使用CRUD Schemas hook
// const { allSchemas } = useCrudSchemas(crudSchemas);
const { allSchemas } = useCrudSchemas(crudSchemas, {
  showTips: true, // 这里必须设置为 true
  defaultFormType: FORM_TYPES.DOMESTIC_COMPONENTS,
});

// ============ 生命周期 ============

/**
 * 组件挂载时初始化
 */
onMounted(async () => {
  // 预加载常用字典
  await dictionaryStore.preloadCommonDictionaries();

  // 设置当前节点名称
  currentNodeName.value = deviceTreeStore.currentTreeNode?.deviceName;
  currentNodeType.value = deviceTreeStore.currentTreeNode?.nodeType; // 设置当前节点类型

  // 注意：不要在mounted中调用getList，让watch的immediate处理
});

defineExpose({
  getList: getListSafe, // 暴露安全版本
});
</script>

<style scoped lang="less">
:deep(.el-divider--horizontal) {
  margin: 5px 0 15px 0;
}

.mb-10px {
  display: flex;
}
:deep(.el-card__body) {
  padding: 20px 0 !important;
}
.line {
      border-top: 1px var(--el-border-color) var(--el-border-style);
    display: block;
    height: 1px;
    margin: 0px 0 10px 0;
    width: 100%;
}
</style>
